<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/18
 * Time: 15:31
 */

namespace app\admin\middleware;


use app\utils\Token;
use think\facade\Cache;

class Check
{
    public function handle($request, \Closure $next) {
        // 登陆不需要token，其它都进去
        if (request()->pathinfo() !== 'account' || !(request()->pathinfo() === 'account' && request()->isPost())) {
            $data = Token::checkToken(request()->header('token'));
            // 判断token是否存在
            if (!$data) {
                return json(['status' => 2, 'message' => 'token不存在']);
            }
            // 校验token是否过期
            if ($data['exp'] < time() || $data['nbf'] > time()) {
                return json(['status' => 2, 'message' => 'token过期']);
            }
            // 判断token是否存在
            $token = Cache::get('token_admin_' . $data['data']->id);
            if (empty($token)) {
                return json(['status' => 2, 'message' => 'token无效']);
            }
            // 判断token是否相等
            if ($token != request()->header('token')) {
                return json(['status' => 2, 'message' => 'token失效']);
            }
            $request->userInfo = $data['data'];
        }
        return $next($request);
    }
}